function solveNQueens(n) {
    const solutions = [];
    const board = Array.from({ length: n }, () => Array(n).fill('.'));

    // 检查当前放置是否有效
    function isValid(row, col) {
        // 检查列
        for (let i = 0; i < row; i++) {
            if (board[i][col] === 'Q') return false;
        }
        // 检查左上对角线
        for (let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
            if (board[i][j] === 'Q') return false;
        }
        // 检查右上对角线
        for (let i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
            if (board[i][j] === 'Q') return false;
        }
        return true;
    }

    // 回溯函数
    function backtrack(row) {
        if (row === n) {
            // 找到一个解，将其加入结果集
            const solution = board.map(r => r.join(''));
            solutions.push(solution);
            return;
        }
        for (let col = 0; col < n; col++) {
            if (isValid(row, col)) {
                // 放置皇后
                board[row][col] = 'Q';
                // 递归尝试下一行
                backtrack(row + 1);
                // 回溯，撤销放置
                board[row][col] = '.';
            }
        }
    }

    backtrack(0);
    return solutions;
}

// 使用示例
const n = 8; // 设置N的大小
const results = solveNQueens(n);
console.log(`共有 ${results.length} 个解`);
results.forEach((solution, index) => {
    console.log(`解 ${index + 1}:`);
    solution.forEach(row => console.log(row));
    console.log('');
});
